package com.dpiinc.TechPage.activity

import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.dpiinc.TechPage.*
import com.dpiinc.TechPage.repository.Status
import com.dpiinc.TechPage.user.utils.ToastUtils
import com.dpiinc.TechPage.viewmodel.OfflineDataViewModel
import com.dpiinc.TechPage.widget.CommDialog
import com.dpiinc.TechPage.widget.LoadingView
import com.beiji.lib.pen.PenManager
import com.beiji.lib.pen.cache.PenCacheManager
import com.beiji.lib.pen.cache.PenCacheStatus
import com.beiji.lib.pen.cache.PenDotCacheHelper
import com.beiji.lib.pen.listener.OfflineDataListener
import com.beiji.lib.pen.model.DotUnit
import com.beiji.lib.pen.model.PenStroke
import kotlinx.android.synthetic.main.activity_offline_data.*
import kotlinx.android.synthetic.main.loading_view.*

/**
 * 离线笔迹
 * Created by X on 2018/7/20.
 */
class OfflineDataActivity : BaseActivity() {

    companion object {
        private val TAG = OfflineDataActivity::class.java.simpleName
    }

    private lateinit var viewModel: OfflineDataViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_offline_data)
        viewModel = ViewModelProviders.of(this)[OfflineDataViewModel::class.java]
        initView()
        startCache()
        PenManager.instance.registerDataCallback(penCallback)
        PenManager.instance.offlineDataCallback = offlineDataCallback
        PenManager.instance.downloadOfflineData()
    }

    private fun initView() {
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        toolbar.setNavigationOnClickListener { showExitConfirm() }
        btn_create_new.setOnClickListener {
            LoadingView.createLoadingViewAndShow(this, 0, getString(R.string.label_edit_note_saving))
            stroke_view.endCache()
            viewModel.isSaveAsNewNote = true
        }
        btn_merge_last.visibility = if (viewModel.lastNote == null) View.GONE else View.VISIBLE
        btn_merge_last.setOnClickListener {
            LoadingView.createLoadingViewAndShow(this, 0, getString(R.string.label_edit_note_saving))
            stroke_view.endCache()
            viewModel.isSaveAsNewNote = false
        }
        viewModel.networkState.observe(this, Observer {
            it ?: return@Observer
            toastIfDebug(it.toString())
            AWLog.e(TAG, it.toString())
            when (it.status) {
                Status.SUCCESS -> {
                    ToastUtils.showCenterTip(this, getString(R.string.toast_offline_data_saved))
                    LoadingView.dismissLoadingView()
                    finish()
                }
                Status.RUNNING -> {
                }
                Status.FAILED -> {
                    //TODO 提交失败处理
                    LoadingView.dismissLoadingView()
                    finish()
                }
            }
        })
    }

    private fun startCache() {
        PenDotCacheHelper.acttype = PenStroke.ACTION_STROKE
        stroke_view.startCache(viewModel.note.noteId)
        PenCacheManager.instance.getCurrentCache()?.liveCacheStatus?.observe(this, Observer {
            it?.let {
                when (it.status) {
                    PenCacheStatus.FINISHED -> {
                        viewModel.save()
                    }
                    else -> {
                    }
                }
            }
        })
    }

    private val penCallback: (DotUnit) -> Boolean = {
        //如果在离线数据页面，书写，接受到的点不做处理，丢弃
        false
    }

    private val offlineDataCallback = object : OfflineDataListener {
        override fun onOfflineDataCount(count: Int) {}
        override fun onOfflineDataDownloadProgress(progress: Int) {
            tv_load_dialog.text = if (progress < 100)
                getString(R.string.label_offline_data_load_progress, progress)
            else
                getString(R.string.label_offline_data_drawing)
        }

        override fun onOfflineDataReceive(dot: DotUnit) {
            dot.actionType = PenStroke.ACTION_STROKE
            stroke_view.drawDot(dot)
        }

        override fun onOfflineDataReceiveProgress(progress: Int) {
            if (progress == 100) {
                loading_view.visibility = View.GONE
//                PenManager.instance.removeOfflineData()
                btn_merge_last.isEnabled = true
                btn_create_new.isEnabled = true
            }
        }
    }

    private fun showExitConfirm() {
        val builder = CommDialog.Builder()
        builder.setMessage(getString(R.string.offline_exit_dialog_message))
                .setLeftButton(getString(R.string.offline_exit_dialog_left_button_text), DialogInterface.OnClickListener { dialogInterface, _ ->
                    dialogInterface.dismiss()
                })
                .setRightButton(getString(R.string.offline_exit_dialog_right_button_text), DialogInterface.OnClickListener { dialogInterface, _ ->
                    dialogInterface.dismiss()
                    PenManager.instance.stopOfflineData()
                    finish()
                })
        builder.build().show(supportFragmentManager)
    }

    override fun onBackPressed() {
        showExitConfirm()
    }

    override fun onDestroy() {
        PenManager.instance.unRegisterDataCallback(penCallback)
        PenManager.instance.offlineDataCallback = null
        super.onDestroy()
    }
}
